package com.hk.yajin.function.members.activity.setting;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.hk.developmentlib.utills.BitmapHelper;
import com.hk.developmentlib.utills.FileHelper;
import com.hk.yajin.R;
import com.hk.yajin.base.BaseActivity;

import org.xutils.common.util.LogUtil;

import java.io.FileOutputStream;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION;
import static android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

/**
 * 类描述：选择拍照和相册的透明activity
 * 创建人：huj
 * 创建时间：2016/4/19 9:43
 */
public class SelectPictureActivity extends BaseActivity implements View.OnClickListener {


    private static final int MSG_GALLERY = 11;    //表示调用相册
    private static final int MSG_CAMERA = 12;    //表示调用相机
    private static final int MSG_CROPPHOTO = 13;    //表示裁剪

    public static final String FILE_NAME = "file_name";                           //拍照存储的文件名
    public static final String PREVIEW_IMAGE_PATH = "preview_image_path";       //预览图片的路径
    public static final String COMPRESS_IMAGE_PATH = "compress_image_path";    //返回数据的key,拍照文件的路径
    public static final String HIDE_ALBUM_BUTTON = "hide_album_button";     //是否隐藏相册选择的按钮
    public static final String IS_CROPPHOTO = "is_cropphoto";               //是否需要裁剪
    public static final String IS_ONLYPICK = "hide_camera_button";               //是否隐藏相机按钮
    //默认图片的名称
    private final String defaultFileName = "default.png";

    //预览图片的地址
    private String previewImagePath;
    //拍照的名称
    private String file_path;
    //压缩后的图片路径
    //private String compress_file_path;
    //是否需要裁剪
    private boolean isCropphoto;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_picture_dialog);
        //getStateBar().setBackgroundColor(XYJUiUtil.getColor(R.color.black_55000000));
        initView();
        initData();
        checkIsOnlyPickImage();
    }

    private void checkIsOnlyPickImage() {
        if (getIntent() != null && getIntent().getBooleanExtra("isOnlyPick", false)) {
            onClick(findViewById(R.id.tv_photo));
        }
    }

    private void initData() {
        previewImagePath = getIntent().getStringExtra(PREVIEW_IMAGE_PATH);
        String fileName = getIntent().getStringExtra(FILE_NAME);
        boolean isHideAlbum = getIntent().getBooleanExtra(HIDE_ALBUM_BUTTON, false);
        boolean isHideCamera = getIntent().getBooleanExtra(IS_ONLYPICK, false);
        isCropphoto = getIntent().getBooleanExtra(IS_CROPPHOTO, true);
        if (TextUtils.isEmpty(fileName)) {
            file_path = FileHelper.getImageDir() + defaultFileName;
            // compress_file_path = FileHelper.getImageDir() + "compress_" + defaultFileName;
        } else {
            file_path = FileHelper.getImageDir() + fileName;
            // compress_file_path = FileHelper.getImageDir() + "compress_" + fileName;
        }

        //隐藏相册选取
        if (isHideAlbum) {
            findViewById(R.id.tv_photo).setVisibility(View.GONE);
            findViewById(R.id.division_line).setVisibility(View.GONE);

        }

        //隐藏相机选取
        if (isHideCamera) {
            findViewById(R.id.tv_photograph).setVisibility(View.GONE);
            findViewById(R.id.division_line).setVisibility(View.GONE);
            ((TextView) findViewById(R.id.tv_photo)).setText("重新上传");
        }
    }

    private void initView() {
        findViewById(R.id.tv_photograph).setOnClickListener(this);
        findViewById(R.id.tv_photo).setOnClickListener(this);
        findViewById(R.id.tv_cancle).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_photograph:    //相机拍照
                requestmMainFunctionPermisson();
                break;

            case R.id.tv_photo:     //相册选取
                Intent it = new Intent(Intent.ACTION_PICK, null);
                it.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(it, MSG_GALLERY);
                break;

            case R.id.tv_cancle:    //取消
                finish();
                break;
        }
    }

    /**
     * 跳转到相机拍照
     */
    public void startPhotograph() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri photoUri = FileProvider.getUriForFile(this, FileHelper.fileProviderAuthorities, FileHelper.makeFileIfNotExists(file_path));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(FileHelper.makeFileIfNotExists(file_path)));
        }
        startActivityForResult(intent, MSG_CAMERA);
    }

    private void requestmMainFunctionPermisson() {
        if (EasyPermissions.hasPermissions(this, permissions[0], permissions[1])) {
            startPhotograph();
        } else {
            EasyPermissions.requestPermissions(this, "为使APP正常运行，请允许以下权限", 100, permissions[0], permissions[1]);
        }
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        requestmMainFunctionPermisson();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        for (String permisson : list) {
            if (EasyPermissions.permissionPermanentlyDenied(this, permisson) && !EasyPermissions.hasPermissions(this, permisson)) {
                new AppSettingsDialog.Builder(this).build().show();
                return;
            }
        }
        requestmMainFunctionPermisson();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            //app在前台显示状态
            if (requestCode == MSG_GALLERY && data != null) { //相册
                if (isCropphoto) {
                    //需要裁剪
                    CropImage(data.getData());
                } else {
                    //不需要裁剪
                    String imagePath = getImagePath(data.getData());
                    compressImage(imagePath);
                }
            } else if (requestCode == MSG_CAMERA) {  //相机
                if (BitmapHelper.readPictureDegree(file_path) != 0) {
                    compressImage(file_path);
                }

                if (isCropphoto) {
                    //需要裁剪
                    Uri photoUri;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        photoUri = FileProvider.getUriForFile(this, FileHelper.fileProviderAuthorities, FileHelper.makeFileIfNotExists(file_path));
                    } else {
                        photoUri = Uri.fromFile(FileHelper.makeFileIfNotExists(file_path));
                    }

                    CropImage(photoUri);
                } else {
                    //不需要裁剪
                    compressImage(file_path);
                }
            } else if (requestCode == MSG_CROPPHOTO) {   //裁剪
                Intent intent = new Intent();
                intent.putExtra(COMPRESS_IMAGE_PATH, file_path);
                setResult(RESULT_OK, intent);
                finish();
            }
        } else {
            finish();
        }
    }


    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void CropImage(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("scale", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 180);
        intent.putExtra("outputY", 180);
        intent.putExtra("return-data", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(FileHelper.makeFileIfNotExists(file_path)));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        startActivityForResult(intent, MSG_CROPPHOTO);
    }


    /**
     * 将图片压缩后存储
     *
     * @param imagePath 需要压缩的图片路径
     */
    private void compressImage(String imagePath) {
        try {
            Bitmap smallBitmap = BitmapHelper.getSmallBitmap(imagePath);
            smallBitmap = BitmapHelper.compressBmpToBytes(smallBitmap, 500);
            smallBitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file_path));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据系统相册返回的url获取图片的路径
     *
     * @param uri 调用系统相册选择图片返回的uri
     * @return 图片绝对路径
     */
    public String getImagePath(Uri uri) {
        if (uri.getScheme().equals("file")) {
            return uri.getPath();
        }

        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(uri,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        return picturePath;
    }


}
